package com.eve.eplus.main.Fragment;

import java.util.ArrayList;
import java.util.HashMap;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.eve.eplus.R;
import com.eve.eplus.common.adapter.HomeContentAdapter;
import com.eve.eplus.common.app.BaseApplication;
import com.eve.eplus.common.app.Constants;
import com.eve.eplus.common.app.SettingConstants;
import com.eve.eplus.common.task.ImageLoader;
import com.eve.eplus.common.view.ComToastTools;
import com.eve.eplus.common.view.PullDownView;
import com.eve.eplus.common.view.PullDownView.OnPullDownListener;
import com.eve.eplus.main.HomeActivity;
import com.eve.eplus.main.logic.SettingUtility;
import com.eve.eplus.sns.SNSContentManager;
import com.eve.eplus.sns.TimeLineProvider;
import com.eve.eplus.sns.weibo.StatusesAPIDef;
import com.eve.eplus.sns.weibo.UsersAPIDef;
import com.eve.eplus.sns.weibo.WeiboAPIGather;

/**
 * 主页面内容Fragment
 * 
 * @author norsie
 * @create 12-11-29
 */
public class ContentFragment extends Fragment implements OnPullDownListener
{

    private final int INIT_FINISH = 9999; // 加载完毕
    private HashMap<String, String> mAccountInfo;
    private ArrayList<HashMap<String, String>> mStates = new ArrayList<HashMap<String, String>>();
    private PullDownView lv;
    private ListView mListView;
    private TextView mAccountName;
    private ImageView mAccountProfile;
    private HomeContentAdapter adapter;
    private int MaxDateNum = 200; // 设置最大的微博条数，超过即不再加载
    private int page = 1;
    private int refreshCode = 0; //  用于判断是否下拉刷新还是查看更多(0第一次1刷新2更多)

    public ContentFragment()
    {
        mAccountInfo = null;
        refreshCode = 0;
        setRetainInstance(true);
    }

    public ContentFragment(HashMap<String, String> accountInfo)
    {
        mAccountInfo = accountInfo;
        refreshCode = 0;
        setRetainInstance(true);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState)
    {
        if (mAccountInfo == null)
        {
            View view = inflater.inflate(R.layout.activity_home_content, null);
            return view;
        }

        View view = inflater.inflate(R.layout.activity_home_content, null);
        mAccountName = (TextView) view.findViewById(R.id.account_name_tv);
        mAccountProfile = (ImageView) view.findViewById(R.id.account_profile_iv);
        lv = (PullDownView) view.findViewById(R.id.listview);
        // 获取账户名称和头像
        new WeiboAPIGather(mAccountInfo, mHandler).getUserShow(mAccountInfo.get(Constants.SNS_UID));
        mAccountName.setText(mAccountInfo.get(Constants.SNS_ACCOUNT_NAME));

        lv.setOnPullDownListener(this);
        mListView = lv.getListView();
        mListView.setOnItemClickListener(onItemClickListener);
        
//        mListView.setOnItemClickListener(onItemClickListener);

        if (SNSContentManager.findRecord(mAccountInfo.get(Constants.SNS_UID)))
            // 获取缓存数据
            new TimeLineProvider(mAccountInfo, mHandler).getTimeline(SNSContentManager.getJsonInfo(mAccountInfo.get(Constants.SNS_UID)));
        else
            // 获取对应数据
            new TimeLineProvider(mAccountInfo, mHandler).getTimeline(page);

        return view;
    }

    @Override
    public void onResume()
    {
        /**
         * 当恢复界面的时候，判断帐号是否已经被删除，若是则重新创建view
         */
            // 获取账户名称和头像
            new WeiboAPIGather(mAccountInfo, mHandler).getUserShow(mAccountInfo.get(Constants.SNS_UID));
            mAccountName.setText(mAccountInfo.get(Constants.SNS_ACCOUNT_NAME));
            super.onResume();
            if (!BaseApplication.SNS_ACCOUNT.contains(mAccountInfo))
                if (getActivity() != null)
                {
                    HomeActivity homeAcitvity = (HomeActivity) getActivity();
                    homeAcitvity.switchContent(new ContentFragment(
                                                                   BaseApplication.SNS_ACCOUNT.get(0)));
                }
    }

    @Override
    public void onDestroy()
    {
        // TODO Auto-generated method stub
        // 清空缓存
        // ImageLoader imageLoader = adapter.getImageLoader();
        // if (imageLoader != null)
        // {
        // imageLoader.clearCache();
        // }
        super.onDestroy();
    }
    
    //Listview项的点击事件
    OnItemClickListener onItemClickListener=new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			ComToastTools.ShowMsg(getActivity(), "详情功能暂未开放", "s");
		}
	};

    private Handler mHandler = new Handler() {

        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case Constants.MSG_TIMELINE_OK:
                    if (refreshCode == 0)
                    {
//                        mStates = TimeLineProvider.getDataList();
                        mStates=(ArrayList<HashMap<String, String>>) msg.obj;
                        adapter = new HomeContentAdapter(getActivity(), mStates);
                        mListView.setAdapter(adapter);
                        lv.enableAutoFetchMore(true, 1);
                        lv.notifyDidLoad();
                        Message m = new Message();
                        m.what = INIT_FINISH;
                        mHandler.sendMessage(m);
                    }
                    else if (refreshCode == 1)
                    {
                        mStates.clear();
//                        mStates = TimeLineProvider.getDataList();
                        mStates=(ArrayList<HashMap<String, String>>) msg.obj;
                        adapter.notifyDataSetChanged();
                        adapter.refresh(mStates);
                        lv.notifyDidRefresh();
                        ComToastTools.ShowTopMsg(getActivity(), "微薄已刷新");
                    }
                    else if (refreshCode == 2)
                    {
                        mStates.remove(adapter.getCount()-1);
                        mStates.addAll(adapter.getCount(),
                                (ArrayList<HashMap<String, String>>) msg.obj);
                        adapter.notifyDataSetChanged();
                        lv.notifyDidMore();
                    }
                    // LogTools.info(mStates.toString());
                    break;
                case Constants.MSG_WEIBO_USERSHOW_OK:
                    if(msg.obj instanceof ArrayList<?>) {
                    String url = ((ArrayList<HashMap<String, String>>)msg.obj).get(0).get(
                            UsersAPIDef.PROFILE_IMAGE_URL);
                    ImageLoader imgLoader = new ImageLoader(getActivity());
                    imgLoader.DisplayImage(url, mAccountProfile, false);
                    }
                    break;
                case INIT_FINISH: // 自动刷新
                    if (SettingUtility.getAutoReflashSetting(true) == SettingConstants.AUTOREFLASH_TRUE)
                        onRefresh();
                    break;
            }
        };
    };

    /**
     * 刷新数据
     */
    @Override
    public void onRefresh()
    {
        // TODO Auto-generated method stub
        page = 1;
        refreshCode = 1;
        new TimeLineProvider(mAccountInfo, mHandler).getTimeline(page);
    }

    /**
     * 加载更多数据
     */
    @Override
    public void onMore()
    {
        // TODO Auto-generated method stub
        if (adapter.getCount() > MaxDateNum)
        {
            ComToastTools.ShowMsg(getActivity(), "已达最大条数", "s");
            return;
        }
        refreshCode = 2;
        page++;
        new TimeLineProvider(mAccountInfo, mHandler).getTimelineMore(adapter.getData().get(
                adapter.getCount() - 1).get(StatusesAPIDef.ID));
    }

    /**
     * 加载更多数据
     */
    private void getMoreData()
    {
    }

}
